package com.staryy.activiti7_workflow.controller;

import com.staryy.activiti7_workflow.pojo.UserInfoBean;
import com.staryy.activiti7_workflow.util.AjaxResponse;
import com.staryy.activiti7_workflow.util.GlobalConfig;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 历史任务接口
 */
@RestController
@RequestMapping("/activitiHistory")
public class ActivitiHistoryController {

    @Autowired
    private HistoryService historyService;

    /**
     * 查询待办任务
     * @return
     */
    @GetMapping("/getInstanceByUserName")
    public AjaxResponse getInstanceByUserName(@AuthenticationPrincipal UserInfoBean userInfoBean){
        try {

            List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(userInfoBean.getUsername())
                    .orderByHistoricTaskInstanceEndTime().desc()
                    .list();
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(),GlobalConfig.ResponseCode.SUCCESS.getDesc(),list);
        } catch (Exception e) {
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.ERRPR.getCode(),"查询用户历史任务失败",e.toString());
        }
    }


    /**
     * 实例历史任务
     * @return
     */
    @GetMapping("/getInstanceByPID")
    public AjaxResponse getInstanceByPID(@RequestParam("piID") String piID){
        try {
            List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(piID)
                    .orderByHistoricTaskInstanceEndTime().desc()
                    .list();
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(),GlobalConfig.ResponseCode.SUCCESS.getDesc(),list);
        } catch (Exception e) {
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.ERRPR.getCode(),"查询实例历史任务失败",e.toString());
        }
    }
}
